/*
 * @# AblumFavorServiceImpl.java 2011-12-30 下午05:44:31
 * 
 * Copyright (C) 2010 - 2011 广州羿安信息科技有限公司
 * Guangzhou ianswer information technology co. ltd.
 * 
 * All rights reserved!
 */
package com.ianswer.px.album.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import com.ianswer.common.orm.PublicDao;
import com.ianswer.common.util.time.SecondsUtils;
import com.ianswer.px.album.entity.AlbumFavor;
import com.ianswer.px.album.redis.AlbumRedis;
import com.ianswer.px.album.service.AlbumFavorService;
import com.ianswer.px.user.entity.UserBaseInfo;

/**
 * @author alvin hwang
 */
@Service("albumFavorService")
public class AblumFavorServiceImpl implements AlbumFavorService {

	@Resource(name = "publicDao")
	private PublicDao publicDao;
	
	@Override
	public List<AlbumFavor> queryFirstPageByUser(Long userId) {
		return queryByUser(userId, 1);
	}
	
	@Override
	public List<AlbumFavor> queryByUser(Long userId, int pageIndex) {
		AlbumFavor cond = new AlbumFavor();
		cond.setUserId(userId);
		
		List<AlbumFavor> favors = publicDao.query("albumsFavors.query", cond);
		if (CollectionUtils.isEmpty(favors)) {
			return new ArrayList<AlbumFavor>();
		}
		for (AlbumFavor favor : favors) {
			favor.setAuthor(UserBaseInfo.get(favor.getAuthorId()));
		}
		return favors;
	}

	@Override
	public Long insert(Long albumId, Long userId) {
		AlbumFavor favor = new AlbumFavor();
		favor.setAlbumId(albumId);
		favor.setUserId(userId);
		favor.setCreatedAt(SecondsUtils.seconds());
		
		Long favorId = (Long) publicDao.insert("albumsFavors.insert", favor);
		
		AlbumRedis.incrFavors(albumId);
		
		return favorId;
	}

	@Override
	public void delete(Long albumId, Long userId) {
		AlbumFavor favor = new AlbumFavor();
		favor.setAlbumId(albumId);
		favor.setUserId(userId);
		
		 publicDao.delete("albumsFavors.delete", favor);
		
		AlbumRedis.decrFavors(albumId);
	}

}
